/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.view.setter;

import foxmob.mlts.component.LinkController;
import foxmob.mlts.controller.setter.QuestionFormController;
import foxmob.mlts.viewcontroller.setter.QuestionForm;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
/**
 *
 * @author Lunayo
 */
public class MultipleFillInBlankSetterPanel extends javax.swing.JPanel {

    /**
     * Creates new form MultipleFillInBlankSetterPanel
     */
    public MultipleFillInBlankSetterPanel(QuestionFormController delegate) {
        initComponents();
        this.delegate = delegate;
        arrayOfString = new ArrayList<String[]>();
        questionText.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
        resetMouseListener();
        previousNumber = 1;
        addDocumentListener();
    }
    
    private void addDocumentListener() {
        questionText.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){
            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent evt) {
                questionTextDocumentChangeUpdate(evt);
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                questionTextDocumentRemoveUpdate(evt);
            }

            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                questionTextDocumentInsertUpdate(evt);
            }
        });
    }
    
    public void setQuestionText(String questionText) {
        this.questionText.setText(questionText);
    }
    
    public String getQuestionText() {
        HTMLDocument doc = getHTMLDocument();
        Element paragraph =
            doc.getElement(doc.getDefaultRootElement(), StyleConstants.NameAttribute, HTML.Tag.P);
        HTMLDocument paragraphDoc = (HTMLDocument) paragraph.getDocument();
        try {
            return paragraphDoc.getText(0, paragraphDoc.getLength());
        } catch (BadLocationException ex) {
            Logger.getLogger(MultipleFillInBlankSetterPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public void addNewCorrectAnswerPanel() {
        MultipleFillInBlankAnswerPanel multipleFillinAnswer = 
                new MultipleFillInBlankAnswerPanel();
        this.correctAnswerPanel.add(multipleFillinAnswer);
    }
  
    public MultipleFillInBlankAnswerPanel getCorrectAnswerTextPanel() {
        if (correctAnswerPanel.getComponentCount() > 0) {
            MultipleFillInBlankAnswerPanel panel =
                    (MultipleFillInBlankAnswerPanel)this.correctAnswerPanel.getComponent(0);
            return panel;
        }
        return null;
    }
    
    public void resetMouseListener() {
        if (questionText.getMouseListeners().length <= 0) return;
        LinkController controller = new LinkController();
        // remove listener
        int length = questionText.getMouseListeners().length;
        for (MouseListener listener : questionText.getMouseListeners()) {
            if (listener instanceof LinkController) {
                questionText.removeMouseListener(listener);
            }
        }
        questionText.addMouseListener(controller);
    }
    
    public void resetCorrectAnswerComponent() {
        if (correctAnswerPanel.getComponentCount() > 0) {
            MultipleFillInBlankAnswerPanel panel =
                    (MultipleFillInBlankAnswerPanel)this.correctAnswerPanel.getComponent(0);
        }
    }
    
    public void resetInputComponent() {
        questionText.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
        resetCorrectAnswerComponent();
        resetObject();
        addDocumentListener();
    }
    
    public JEditorPane getQuestionTextArea() {
        return this.questionText;
    }
    
    public void setDelegate(QuestionFormController delegate) {
        this.delegate = delegate;
    }
    
    public JPanel getCorrectAnswerPanel() {
        return this.correctAnswerPanel;
    }
    
    public HTMLDocument getHTMLDocument() {
        return (HTMLDocument)getQuestionTextArea().getDocument();
    }
    
    public void setHTMLDocument(HTMLDocument questionDocument) {
        getQuestionTextArea().setDocument(questionDocument);
        addDocumentListener();
    }
    
    public void insertOrUpdateCorrectAnswer(String[] string, int number) {
        if (arrayOfString.size() >= number) {
            arrayOfString.set(number - 1, string);
        } else {
            if (string.length > 0) {
                arrayOfString.add(number - 1, string);
            }
        }
    }
    
    public void setCorrectAnswer(int number) {
        if (correctAnswerPanel.getComponentCount() == 0) {
            addNewCorrectAnswerPanel();
        } 
        
        MultipleFillInBlankAnswerPanel panel =
                (MultipleFillInBlankAnswerPanel)this.correctAnswerPanel.getComponent(0);
        if (arrayOfString.size() >= number) {
            panel.setCorrectAnswer(arrayOfString.get(number - 1));
        } else {
            resetCorrectAnswerComponent();
        }
        panel.setNumber(number);
    }
    
    public void setListOfAnswer(List<String[]> answer) {
        this.arrayOfString = answer;
    }
    
    public List<String[]> getCorrectAnswer() {
        return this.arrayOfString;
    }
    
    public void setPreviousNumber(int number) {
        this.previousNumber = number;
    }
    
    public int getPreviousNumber() {
        return this.previousNumber;
    }
    
    public void resetObject() {
        this.previousNumber = 1;
        this.arrayOfString = new ArrayList<String[]>();
        setCorrectAnswer(previousNumber);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        questionLabel = new javax.swing.JLabel();
        addBlanksButton = new javax.swing.JButton();
        correctAnswerPanel = new javax.swing.JPanel();
        correctAnswerLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        questionText = new javax.swing.JEditorPane();

        questionLabel.setText("Question :");

        addBlanksButton.setText("Add Blanks");
        addBlanksButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBlanksButtonActionPerformed(evt);
            }
        });

        correctAnswerPanel.setLayout(new javax.swing.BoxLayout(correctAnswerPanel, javax.swing.BoxLayout.Y_AXIS));

        correctAnswerLabel.setText("CorrectAnswer :");

        questionText.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
            public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
                questionTextHyperlinkUpdate(evt);
            }
        });
        jScrollPane1.setViewportView(questionText);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(addBlanksButton))
                    .add(correctAnswerPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(questionLabel)
                            .add(correctAnswerLabel))
                        .add(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(questionLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(addBlanksButton)
                .add(2, 2, 2)
                .add(correctAnswerLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(correctAnswerPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addBlanksButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addBlanksButtonActionPerformed
        // TODO add your handling code here:
        try {
            delegate.addCorrectAnswerDidTap(addBlanksButton);
        } catch (Exception e) {
            System.err.print("Error : Method was not found" + e.getMessage());
        }
    }//GEN-LAST:event_addBlanksButtonActionPerformed

    private void questionTextHyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {//GEN-FIRST:event_questionTextHyperlinkUpdate
        // TODO add your handling code here:
        try {
            delegate.hyperlinkTextDidTap(evt);
        } catch (Exception e) {
            System.err.print("Error : Method was not found" + e.getMessage());
        }
    }//GEN-LAST:event_questionTextHyperlinkUpdate

    private void questionTextDocumentChangeUpdate(javax.swing.event.DocumentEvent evt) {
        try {
            delegate.questionTextDocumentDidChange(evt);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }
    
    private void questionTextDocumentInsertUpdate(javax.swing.event.DocumentEvent evt) {
        try {
            delegate.questionTextDocumentDidInsert(evt);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }
    
    private void questionTextDocumentRemoveUpdate(javax.swing.event.DocumentEvent evt) {
        try {
            delegate.questionTextDocumentDidRemove(evt);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addBlanksButton;
    private javax.swing.JLabel correctAnswerLabel;
    private javax.swing.JPanel correctAnswerPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel questionLabel;
    private javax.swing.JEditorPane questionText;
    // End of variables declaration//GEN-END:variables

    private QuestionFormController delegate;
    private List<String[]> arrayOfString;
    private int previousNumber;
}
